<?php
class settingController extends commonController{
	
	private $type = array();
	
	public function __construct(){
		parent::__construct();
		
	}
	/**
	 * 更改密码
	 */
	public function changePassword(){
		
		if(isPost()){
			$oldPassword = md5($_POST['oldpassword']);
			$adminName = session('username');
			$user = array();
			$user = M('admin')->where("username = '{$adminName}' and password = '{$oldPassword}'")->getOne();
			if(!empty($user)){
				M('admin')->update("id = {$user['id']}",array('password'=>md5($_POST['newpassword'])));
				echo '<span>修改成功</span>';
			}else{
				echo '<span>原密码错误</span>';
			}
		}else{
			$this->display('changePassword.html');
		}
		
	}
	
	/**
	 * 基础设置
	 */
	public function basic(){
		
		if(isPost()){
			$data = array();
			foreach($_POST as $k=>$v){
				M('setting')->update("`key` = '{$k}'",array('value'=>$v));
				$data[strtolower($k)] = $v;
			}
			//生成siteinfo.php
			$content = "<?php \r\n return ";
			$content .= var_export($data,true);
			$content .= "\r\n?>";
// 			@file_put_contents(ROOT_PATH."/config/siteinfo.php", $content);
			wfile(ROOT_PATH."/config/siteinfo.php", $content);
		}
		$data = M('setting')->where()->getAll();
		$viewPath = ROOT_PATH.'/view/theme/';
		$themeArr = getDir($viewPath);
		$themeArr = array_flip($themeArr);
// 		unset($themeArr['admin']);//后台模板
// 		unset($themeArr['.svn']);//剔除.svn信息
		$themeArr = array_flip($themeArr);
		if(!empty($data) && is_array($data)){
			foreach ($data as &$item){
				if($item['key'] == 'theme'){
					$item['defaultValue'] = $themeArr;
				}
			}
		}
		
		$this->assign('data', $data);
		$this->display('basic.html');
	}
	
	public function theme(){
		$viewPath = ROOT_PATH.'/view/';
		$themeArr = getDir($viewPath);
// 		debug($themeArr);
		$this->display('theme.html');
	}
	/**
	 * 头部导航
	 */
	public function headerNav(){
		if(isPost()){
			$nav = $navFile = array();
			$siteUrl = '';
			foreach($_POST['type'] as $k=>$v){
				$arr = array();
				$arr['type'] = $v;
				$arr['id'] = $_POST['cate'][$k];
				$arr['name'] = $_POST['name'][$k];
				$nav[] = $arr;
				
				switch ($arr['type']){
					
					case 'system':
						if($arr['id'] == 0){
// 							$arr['url'] = $siteUrl.'index.php';
							$arr['url'] = array();
						}else{
							$mod = M('mod')->where('id='.$arr['id'])->getOne();
							//$arr['url'] = U('default/'.$mod['mod'].'/index');
							$arr['url'] = array('str'=>'default/'.$mod['mod'].'/index','param'=>array());
						}
						break;
					case 'page':
						$page = M('page')->where('id='.$arr['id'])->getOne();
// 						$arr['url'] = U('default/page/detail',array('name'=>$page['shortname']));
						$arr['url'] = array('str'=>'default/page/detail','param'=>array('name'=>$page['shortname']));
						break;
					case 'guestbook':
// 						$arr['url'] = U('default/guestbook/index');
						$arr['url'] = array('str'=>'default/guestbook/index','param'=>array());
						break;
					default:
// 						$arr['url'] = U('default/'.$arr['type'].'/clist',array('cid'=>$arr['id']));//clist cate list分类列表
						$arr['url'] = array('str'=>'default/'.$arr['type'].'/clist','param'=>array('cid'=>$arr['id']));
						break;
				}
				
				$navFile[] = $arr;
			}
// 			debug($navFile);
			$data = array();
			$data['name'] = '头部导航';
// 			$data['key'] = 'header';
			$data['value'] = serialize($nav);
			$data['updatetime'] = time();
// 			debug($data,0);
			$arr = M('nav')->field('`key`')->where("`key` ='header'")->getOne();
			if($arr['key'] == '' || empty($arr['key'])){
				$data['key'] = 'header';
				M('nav')->insert($data);
			}else{
				M('nav')->update("`key` ='header'",$data);
			}
			//生成url.php
			$content = "<?php \r\n return ";
			$content .= var_export($navFile,true);
			$content .= "\r\n?>";
			wfile(ROOT_PATH."/config/nav.php", $content);
			redirect(U('admin/setting/headerNav'));
		}else{
			$data = M('mod')->field()->where('`issystem` = 1')->getAll();
			if(is_array($data)){
				foreach($data as $v){
					$this->type[$v['mod']] = $v['name'];
				}
			}
			$this->type['page'] = '单页';
			$this->type['system'] = '系统';
			
			
			//现有导航
			$headerNav = M('nav')->where('`key` = "header"')->getOne();
			$headerNav['value'] = unserialize($headerNav['value']);
			
			if(!empty($headerNav['value']) && is_array($headerNav['value'])){
				foreach ($headerNav['value'] as  $k=>&$v){
					switch ($v['type']){
						case 'page':
							//page;
							$arr = M('page')->field('id,title AS name')->where()->getAll();
							break;
						case 'system':
							$arr = M('mod')->field('id,name')->where('issystem = 1')->getAll();//系统模块
							array_push($arr, array('id'=>0,'name'=>'首页'));//system下 id为0 的是首页
							$tmp = array();
							foreach ($arr as $ik=>$iv){
								$tmp[$iv['id']] = $iv;
							}
							$arr = $tmp;
							break;
						case 'guestbook':
							$arr = array(array('id'=>0,'name'=>'留言'));//guestbook下 id为0 的是留言板页面
							break;
						default:
							//模块下的分类
							$arr = M('category')->field('id,categoryname AS name,parentid')->where("type = '{$v['type']}'")->getAll();
							break;
					}
					$v['cates'] = $arr;
					unset($arr);
				}
			}
			
			//js tr index
			$index = 0;
			if(is_array($headerNav) && !empty($headerNav)){
				$index = intval(count($headerNav))-1;
			}
			
			$this->assign('type', $this->type);
			$this->assign('index', $index);
			$this->assign('headerNav', $headerNav);
			
			$this->display('headerNav.html');
		}
		
	}
	/**
	 * 底部导航
	 */
	public function footerNav(){
		
		$this->display('footerNav.html');
	}
	
	public function systemMod(){
		
		$this->display('systemMod.html');
	}
	
	public function getCate(){
		$type = trim($_GET['type']);
		$data = array();
		switch ($type){
			case 'page':
				//page;
				$data = M('page')->field('id,title AS name')->where()->getAll();
				break;
			case 'system':
				$data = M('mod')->field('id,name')->where('issystem = 1')->getAll();//系统模块
				array_push($data, array('id'=>0,'name'=>'首页'));//system下 id为0 的是首页
				break;
			case 'guestbook':
				$data = array(array('id'=>0,'name'=>'留言'));//guestbook下 id为0 的是留言板页面
				break;
			default:
				//模块下的分类
				//$data = M('category')->field('id,categoryname AS name')->where("type = '{$type}' AND parentid != 0 ")->getAll();
				$data = M('category')->field('id,categoryname AS name,parentid')->where("type = '{$type}' ")->getAll();
				break;
		}
		if($data){
			jsonOUT(array('result'=>true,'data'=>$data));
		}else{
			jsonOUT(array('result'=>false, 'data'=>array('reason'=>'数据查询失败')));
		}
	}
	/**
	 * 数据库备份管理
	 */
	public function backupDB(){
		$data = array();
		//$data = M('backup')->getAll();
		$backupPath = "/static/backup/";
		//读取文件夹
		$dir = ROOT_PATH.$backupPath;
		if (is_dir($dir)){
			if ($dh = opendir($dir)){
				while (($file = readdir($dh))!= false){
					//文件名的全路径 包含文件名
					$filePath = $dir.$file;
					if(!is_dir($filePath)){
						//获取文件修改时间
						$fmt = filemtime($filePath);
						//echo "<span style='color:#666'>(".date("Y-m-d H:i:s",$fmt).")</span> ".$filePath."<br/>";
						$tmp = array();
						$tmp['name'] = basename($filePath);
						$tmp['path'] = $filePath;
						$tmp['createtime'] = $fmt;
						$tmp['basecode'] = base64_encode($filePath);
							
						$data[] = $tmp;
					}
					
				}
				closedir($dh);
			}
		}
		
		$this->assign('data', $data);
		
		$this->display('backupDB.html');
	}
	/**
	 * 创建新备份
	 */
	public function createBackup(){
		$backupPath = "/static/backup/";
		$config_db = config('db');
		// 备份数据库
		$host = $config_db['db_host'];
		$user = $config_db['db_user'];
		// 数据库账号
		$password = $config_db['db_pwd'];
		// 数据库密码
		$dbname = $config_db['db_database'];
		// 数据库名称
		// 这里的账号、密码、名称都是从页面传过来的
		if (! mysql_connect ( $host, $user, $password )) // 连接mysql数据库
		{
			echo '数据库连接失败，请核对后再试';
			exit ();
		}
		if (! mysql_select_db ( $dbname )) // 是否存在该数据库
		{
			echo '不存在数据库:' . $dbname . ',请核对后再试';
			exit ();
		}
		mysql_query ( "set names 'utf8'" );
		$mysql = "set charset utf8;\r\n";
		$q1 = mysql_query ( "show tables" );
		while ( $t = mysql_fetch_array ( $q1 ) ) {
			$table = $t [0];
			$q2 = mysql_query ( "show create table `$table`" );
			$sql = mysql_fetch_array ( $q2 );
// 			debug($sql);
			$mysql .= "DROP TABLE IF EXISTS `{$sql['Table']}` ;\r\n";
			$mysql .= $sql['Create Table'] . ";\r\n";
			$q3 = mysql_query ( "select * from `$table`" );
			while ( $data = mysql_fetch_assoc ( $q3 ) ) {
				$keys = array_keys ( $data );
				$keys = array_map ( 'addslashes', $keys );
				$keys = join ( '`,`', $keys );
				$keys = "`" . $keys . "`";
				$vals = array_values ( $data );
				$vals = array_map ( 'addslashes', $vals );
				$vals = join ( "','", $vals );
				$vals = "'" . $vals . "'";
				$mysql .= "insert into `$table`($keys) values($vals);\r\n";
			}
		}
		$filePath = ROOT_PATH.$backupPath;
		$filename = $dbname . date ( 'YmdGi' ) . ".sql"; // 存放路径，默认存放到项目最外层
		$fp = fopen ( $filePath.$filename, 'w' );
		fputs ( $fp, $mysql );
		fclose ( $fp );
// 		echo "数据备份成功";
		
// 		$res = M('backup')->insert(array('name'=>basename($filename),'path'=>$backupPath.$filename,'createtime'=>time()));
// 		if($res){
// 			redirect(U('admin/setting/backupDB'));
// 		}
		redirect(U('admin/setting/backupDB'));
		
	}
	/**
	 * 还原备份
	 */
	public function restoreBackup(){
		$code = $_GET['code'];
		
		//$backup = M('backup')->where('id='.$id)->getOne();
		// 恢复数据库
		$config_db = config('db');
		// 备份数据库
		$host = $config_db['db_host'];
		$user = $config_db['db_user'];
		// 数据库账号
		$password = $config_db['db_pwd'];
		// 数据库密码
		$dbname = $config_db['db_database'];
		mysql_connect ( $host, $user, $password );
		mysql_select_db ( $dbname );
		$mysql_file = base64_decode($code); // 指定要恢复的MySQL备份文件路径,请自已修改此路径
		$this->restore ( $mysql_file ); // 执行MySQL恢复命令
		
	}
	/**
	 * 删除备份
	 */
	public function delBackup(){
		$code = $_GET['code'];
		$mysql_file = base64_decode($code);
		if(is_file($mysql_file)){
			if(file_exists($mysql_file)){
				@unlink($mysql_file);
			}
		}
		redirect(U('admin/setting/backupDB'));
	}
	
	function restore($fname) {
		if (file_exists ( $fname )) {
			$sql_value = "";
			$cg = 0;
			$sb = 0;
			$sqls = file ( $fname );
			foreach ( $sqls as $sql ) {
				$sql_value .= $sql;
			}
			$a = explode ( ";\r\n", $sql_value ); // 根据";\r\n"条件对数据库中分条执行
			$total = count ( $a ) - 1;
			for($i = 0; $i < $total; $i ++) {
				// 执行命令
				if (mysql_query ( $a [$i] )) {
					$cg += 1;
				} else {
					$sb += 1;
					$sb_command [$sb] = $a [$i];
				}
			}
			echo "操作完毕，共处理 $total 条命令，成功 $cg 条，失败 $sb 条";
			// 显示错误信息
			if ($sb > 0) {
				echo "<hr><br><br>失败命令如下：<br>";
				for($ii = 1; $ii <= $sb; $ii ++) {
					echo "<p><b>第 " . $ii . " 条命令（内容如下）：</b><br>" . $sb_command [$ii] . "</p><br>";
				}
			} // -----------------------------------------------------------
		} else {
			echo "MySQL备份文件不存在，请检查文件路径是否正确！";
		}
	}
}